package com.xiaohui.user.init;

import com.alibaba.fastjson.JSON;
import com.xiaohui.user.entity.po.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 服务预热
 */
@Component
@Slf4j
public class ApplicationInit implements ApplicationListener<ApplicationReadyEvent> {


    Map<String, InitFunction> initFunctionMap = new HashMap<>();

    {
        initFunctionMap.put("预热fastJson", this::initFastJson);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        System.out.println("服务启动完成");
        try {
            initFunctionMap.forEach((k, v) -> {
                System.out.println("执行初始化函数：" + k);
                long start = System.currentTimeMillis();
                v.invoke();
                log.info("初始化函数执行耗时：{}ms", System.currentTimeMillis() - start);
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public interface InitFunction {
        void invoke();
    }


    /**
     * 案例
     */
    private void initFastJson() {
        SysUser user = new SysUser();
        user.setName("xiaohui");
        String s = JSON.toJSONString(user);
        System.out.println(s);
        JSON.parseObject(s, SysUser.class);
    }
}
